from flask import Blueprint, request, jsonify
from app.models import db, Student, Honor
from app.utils import token_required
import datetime
from flask import current_app as app, current_app
from sqlalchemy import extract, desc
import os
from werkzeug.utils import secure_filename
from . import student_api_bp
from werkzeug.security import generate_password_hash, check_password_hash

@student_api_bp.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    role = data.get('role')
    username = data.get('username')
    name = data.get('name')
    gender = data.get('gender')
    password = data.get('password')
    confirm = data.get('confirm')
    grade = data.get('grade')
    class_name = data.get('class_name')
    department = data.get('department')

    if not all([role, username, name, gender, password, confirm]):
        return jsonify({'code': 400, 'msg': '信息填写不完整'}), 400
    if password != confirm:
        return jsonify({'code': 400, 'msg': '两次输入的密码不一致'}), 400
    if Student.query.filter_by(username=username).first():
        return jsonify({'code': 400, 'msg': '用户名已存在'}), 400
    student = Student(role=role, username=username, name=name, gender=gender)
    if role == 'student':
        student.grade = grade
        student.class_name = class_name
        student.department = department
    elif role == 'teacher':
        student.department = department
    student.password_hash = generate_password_hash(password)
    db.session.add(student)
    db.session.commit()
    return jsonify({'code': 200, 'msg': '注册成功'})

# 示例：学生荣誉提交
@student_api_bp.route('/honor', methods=['POST'])
@token_required
def add_honor(current_user):
    # 支持表单提交
    if request.content_type and request.content_type.startswith('multipart/form-data'):
        title = request.form.get('title')
        honor_type = request.form.get('honor_type')
        rank = request.form.get('rank')
        level = request.form.get('level')
        date = request.form.get('date')
        organization = request.form.get('organization')
        description = request.form.get('description')
        file = request.files.get('certificate')
        certificate_url = None
        if file and file.filename:
            filename = secure_filename(file.filename)
            save_path = os.path.join(os.path.dirname(__file__), '../../static/certificates')
            os.makedirs(save_path, exist_ok=True)
            file_path = os.path.join(save_path, filename)
            file.save(file_path)
            certificate_url = f'/static/certificates/{filename}'
    else:
        data = request.json
        title = data.get('title')
        honor_type = data.get('honor_type')
        rank = data.get('rank')
        level = data.get('level')
        date = data.get('date')
        organization = data.get('organization')
        description = data.get('description')
        certificate_url = data.get('certificate_url')
    if not title or not honor_type or not level or not date or not organization or not rank:
        return jsonify({'code': 400, 'msg': '请填写完整信息'}), 400
    honor = Honor(
        student_id=current_user.id,
        title=title,
        honor_type=honor_type,
        rank=rank,
        level=level,
        date=date,
        organization=organization,
        description=description,
        certificate_url=certificate_url,
        created_at=datetime.datetime.now()
    )
    db.session.add(honor)
    db.session.commit()
    return jsonify({'code': 200, 'msg': '荣誉提交成功'}) 

@student_api_bp.route('/honor/edit/<int:honor_id>', methods=['POST'])
@token_required
def edit_honor(current_user, honor_id):
    honor = Honor.query.filter_by(id=honor_id, student_id=current_user.id).first()
    if not honor:
        return jsonify({'code': 404, 'msg': '未找到该荣誉'}), 404
    # 支持表单和json
    if request.content_type and request.content_type.startswith('multipart/form-data'):
        honor.title = request.form.get('title')
        honor.honor_type = request.form.get('honor_type')
        honor.rank = request.form.get('rank')
        honor.level = request.form.get('level')
        honor.organization = request.form.get('organization')
        honor.date = request.form.get('date')
        honor.description = request.form.get('description')
        file = request.files.get('certificate')
        if file and file.filename:
            filename = secure_filename(file.filename)
            save_path = os.path.join(os.path.dirname(__file__), '../../static/certificates')
            os.makedirs(save_path, exist_ok=True)
            file_path = os.path.join(save_path, filename)
            file.save(file_path)
            honor.certificate_url = f'/static/certificates/{filename}'
    else:
        data = request.json
        honor.title = data.get('title')
        honor.honor_type = data.get('honor_type')
        honor.rank = data.get('rank')
        honor.level = data.get('level')
        honor.organization = data.get('organization')
        honor.date = data.get('date')
        honor.description = data.get('description')
        honor.certificate_url = data.get('certificate_url')
    db.session.commit()
    return jsonify({'code': 200, 'msg': '修改成功'})

@student_api_bp.route('/honor/delete/<int:honor_id>', methods=['POST'])
@token_required
def delete_honor(current_user, honor_id):
    honor = Honor.query.filter_by(id=honor_id, student_id=current_user.id).first()
    if not honor:
        return jsonify({'code': 404, 'msg': '未找到该荣誉'}), 404
    db.session.delete(honor)
    db.session.commit()
    return jsonify({'code': 200, 'msg': '删除成功'})

@student_api_bp.route('/info', methods=['GET'])
@token_required
def get_student_info(current_user):
    info = {
        'id': current_user.id,
        'role': 'student',
        'username': current_user.username,
        'name': current_user.name,
        'gender': current_user.gender,
        'grade': current_user.grade,
        'class_name': current_user.class_name,
        'department': current_user.department,
        'phone': current_user.phone,      # 新增
        'email': current_user.email,      # 新增
        'avatar_url': current_user.avatar_url  # 新增头像字段
    }
    return jsonify({'code': 200, 'user': info})

@student_api_bp.route('/profile', methods=['POST'])
@token_required
def update_profile(current_user):
    data = request.get_json()
    # 只更新有提交的字段
    if 'phone' in data:
        current_user.phone = data['phone'].strip()
    if 'email' in data:
        current_user.email = data['email'].strip()
    db.session.commit()
    return jsonify({'code': 200, 'msg': '保存成功'})

@student_api_bp.route('/password', methods=['POST'])
@token_required
def change_password(current_user):
    data = request.get_json()
    old_password = data.get('old_password')
    new_password = data.get('new_password')
    if not old_password or not new_password:
        return jsonify({'code': 400, 'msg': '请填写完整'}), 400
    if not check_password_hash(current_user.password_hash, old_password):
        return jsonify({'code': 400, 'msg': '原密码错误'}), 400
    current_user.password_hash = generate_password_hash(new_password)
    db.session.commit()
    return jsonify({'code': 200, 'msg': '修改成功'})

@student_api_bp.route('/honor/summary', methods=['GET'])
@token_required
def honor_summary(current_user):
    honors = Honor.query.filter_by(student_id=current_user.id).all()
    total = len(honors)
    this_year = datetime.datetime.now().year
    year_count = sum(1 for h in honors if h.date and str(this_year) in h.date)
    level_order = {'国家级': 4, '省级': 3, '校级': 2, '院级': 1}
    highest = None
    if honors:
        highest = max((h.level for h in honors if hasattr(h, 'level')), key=lambda l: level_order.get(l, 0), default=None)
    return jsonify({'code': 200, 'total': total, 'year_count': year_count, 'highest': highest or ''})

@student_api_bp.route('/honor/mine', methods=['GET'])
@token_required
def get_my_honors(current_user):
    honor_type_ = request.args.get('type', '').strip()
    year = request.args.get('year', '').strip()
    query = Honor.query.filter_by(student_id=current_user.id)
    if honor_type_:
        query = query.filter_by(honor_type=honor_type_)
    if year:
        query = query.filter(Honor.date.like(f'{year}%'))
    honors = query.order_by(Honor.created_at.desc()).all()
    honor_list = [
        {
            'id': h.id,
            'title': h.title,
            'honor_type': getattr(h, 'honor_type', ''),
            'rank': getattr(h, 'rank', ''),
            'level': getattr(h, 'level', ''),
            'date': h.date,
            'certificate_url': h.certificate_url,
            'description': h.description,
            'created_at': h.created_at.strftime('%Y-%m-%d %H:%M'),
            'summary': (h.description or '')[:40],
        } for h in honors
    ]
    return jsonify({'code': 200, 'honors': honor_list})

@student_api_bp.route('/honor/detail/<int:honor_id>', methods=['GET'])
@token_required
def honor_detail(current_user, honor_id):
    honor = Honor.query.filter_by(id=honor_id, student_id=current_user.id).first()
    if not honor:
        return jsonify({'code': 404, 'msg': '未找到该荣誉'}), 404
    honor_info = {
        'id': honor.id,
        'title': honor.title,
        'honor_type': getattr(honor, 'honor_type', ''),
        'rank': getattr(honor, 'rank', ''),
        'level': getattr(honor, 'level', ''),
        'date': honor.date,
        'organization': honor.organization,
        'certificate_url': honor.certificate_url,
        'description': honor.description,
        'created_at': honor.created_at.strftime('%Y-%m-%d %H:%M'),
    }
    return jsonify({'code': 200, 'honor': honor_info})

@student_api_bp.route('/delete_account', methods=['POST'])
@token_required
def delete_account(current_user):
    # 级联删除荣誉（如模型已设置cascade可省略）
    # Honor.query.filter_by(student_id=current_user.id).delete()
    from app.models import db
    db.session.delete(current_user)
    db.session.commit()
    return jsonify({'code': 200, 'msg': '账号已注销'}) 

@student_api_bp.route('/avatar', methods=['POST'])
@token_required
def upload_avatar(current_user):
    file = request.files.get('avatar')
    if not file or not file.filename:
        return jsonify({'code': 400, 'msg': '未选择文件'}), 400
    filename = secure_filename(file.filename)
    # 防止重名，加入用户id和时间戳
    import time
    ext = filename.rsplit('.', 1)[-1] if '.' in filename else ''
    filename = f"avatar_{current_user.id}_{int(time.time())}.{ext}"
    save_dir = os.path.join(os.path.dirname(__file__), '../../static/avatars')
    os.makedirs(save_dir, exist_ok=True)
    file_path = os.path.join(save_dir, filename)
    file.save(file_path)
    avatar_url = f'/static/avatars/{filename}'
    current_user.avatar_url = avatar_url
    db.session.commit()
    return jsonify({'code': 200, 'msg': '上传成功', 'avatar_url': avatar_url}) 